<!--图文管理-->
<template>
  <div id="thirdWechatArticle" class="app-container">
    <!--搜索条件-->
    <div class="filter-container">
      <el-form :model="listQuery" :inline="true">
        <el-form-item>
          <application-key-select v-model="listQuery.appId" :type="listQuery.type" />
        </el-form-item>
        <el-form-item>
          <el-input v-model="listQuery.keyword" placeholder="请输入关键字" @keyup.enter.native="handleFilter" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" plain @click="handleFilter">搜索</el-button>
          <el-button icon="el-icon-refresh" plain @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!--列表-->
    <div class="table-container flex-main">
      <div class="table-container-header">
        <table-toolbar @create="handleCreate" @refresh="handleFilter" @remove="removeRecord" />
      </div>
      <el-table
        ref="multipleTable"
        :data="list"
        header-cell-class-name="table-header"
        fit
        height="100%"
        highlight-current-row
        @selection-change="handleSelectionChange"
        @row-click="handleRowClick"
        @sort-change="sortChange">
        <el-table-column type="selection" width="60" />
        <el-table-column align="center" prop="id" label="#" width="60">
          <template slot-scope="scope">{{ scope.$index+1 }}</template>
        </el-table-column>
        <el-table-column label="封面" prop="avatar" width="70" align="center">
          <template slot-scope="scope">
            <img :src="global.getFileView(scope.row.photo)" class="common-round-image-32" :title="scope.row.title" @error="handleImageError">
          </template>
        </el-table-column>
        <el-table-column label="标题" prop="title" min-width="100" sortable show-overflow-tooltip />
        <el-table-column label="作者" prop="author" min-width="100" sortable show-overflow-tooltip />
        <el-table-column label="摘要" prop="summary" min-width="100" sortable show-overflow-tooltip />
        <el-table-column label="附件" prop="attachment" min-width="100" sortable show-overflow-tooltip />
        <el-table-column label="原创" prop="isOriginal" width="100" sortable>
          <template slot-scope="scope">{{ scope.row.isOriginal==0 ?'摘抄':'原创' }}</template>
        </el-table-column>
        <el-table-column label="摘抄自" prop="extractFrom" min-width="100" sortable show-overflow-tooltip />
        <el-table-column prop="gmtModified" sortable label="修改时间" width="160">
          <template slot-scope="scope">{{ scope.row.gmtModified | formatDate }}</template>
        </el-table-column>
        <el-table-column label="操作" align="center" fixed="right" width="90">
          <template slot-scope="scope">
            <button-option icon="el-icon-edit" skin="primary" title="编辑" @click="handleUpdate(scope.row)" />
            <button-option icon="el-icon-delete" skin="danger" title="删除" @click="handleRemoveSingle(scope.row)" />
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div class="pagination_handler">
      <pagination v-show="total>0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit" @pagination="fetchData" />
    </div>

    <!--新增/编辑侧边栏-->
    <side-box :show="sideBox.recordShow" :title="sideBox.title" :width="'calc(100% - 20px)'" class="side-modal-box-full" @close="sideBox.recordShow = !sideBox.recordShow">
      <template slot="body">
        <el-form
          ref="dataForm"
          :rules="thirdWechatArticleRules"
          :model="thirdWechatArticleRecord"
          label-position="right"
          label-width="120px">
          <el-form-item label="封面:" prop="photo">
            <single-image-upload
              ref="logo"
              v-model="thirdWechatArticleRecord.photo"
              :catalog="constants.FILE_CATALOG_WECHAT_ARTICLE_PHOTO" />
          </el-form-item>
          <el-form-item label="标题:" prop="title">
            <el-input v-model="thirdWechatArticleRecord.title" maxlength="40" show-word-limit placeholder="请输入" />
          </el-form-item>
          <el-form-item label="作者:" prop="author">
            <el-input v-model="thirdWechatArticleRecord.author" maxlength="20" show-word-limit placeholder="请输入" />
          </el-form-item>
          <el-form-item label="所属分类:" prop="categoryId">
            <el-select-tree v-model="thirdWechatArticleRecord.categoryId" :data="categories" :props="{children: 'children', label: 'name'}" />
          </el-form-item>
          <el-form-item label="是否原创:" prop="isOriginal">
            <el-radio-group v-model="thirdWechatArticleRecord.isOriginal">
              <el-radio :label="0">否</el-radio>
              <el-radio :label="1">是</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="摘抄自:" prop="extractFrom">
            <el-input v-model="thirdWechatArticleRecord.extractFrom" maxlength="50" show-word-limit placeholder="请输入" />
          </el-form-item>
          <el-form-item label="留言:" prop="leavingMessage">
            <el-radio-group v-model="thirdWechatArticleRecord.leavingMessage">
              <el-radio :label="0">禁止留言</el-radio>
              <el-radio :label="1">所有人可留言</el-radio>
              <el-radio :label="1">仅粉丝可留言</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="摘要:" prop="summary">
            <el-input
              v-model="thirdWechatArticleRecord.summary"
              :rows="4"
              type="textarea"
              maxlength="200"
              show-word-limit
              placeholder="请输入摘要" />
          </el-form-item>
          <el-form-item label="附件:" prop="attachment1">
            <simple-uploader v-model="thirdWechatArticleRecord.attachment1" :mode="['file']" :catalog="constants.FILE_CATALOG_WECHAT_ARTICLE_ATTACHMENT" />
          </el-form-item>
          <el-form-item label="内容:" prop="contentBody" class="ue-container">
            <Editor v-model="thirdWechatArticleRecord.content" :catalog="constants.FILE_CATALOG_WECHAT_ARTICLE_CONTENT" />
          </el-form-item>

        </el-form>
      </template>
      <template slot="foot">
        <el-button type="primary" plain @click="sideBox.status==='create'?createData():updateData()">保存 </el-button>
      </template>
    </side-box>
  </div>
</template>

<script>
import applicationKeySelect from '../applicationKeySelect'
export default {
  components: { applicationKeySelect },

  data() {
    return {

      categories: [],
      list: [],
      total: 0,
      listQuery: {
        appId: '',
        type: 1,
        page: 1,
        limit: this.common.PAGE_LIMIT_DEFAULT,
        keyword: undefined,
        sort: this.common.SORT_DEFAULT
      },

      multipleSelectionRecords: [],
      // 固定写法
      sideBox: {
        recordShow: false,
        title: '',
        status: 'create'
      },
      thirdWechatArticleRecord: {},
      thirdWechatArticleRules: {
        title: [
          { required: true, message: '请输入标题', trigger: 'blur' }
        ],
        author: [
          { required: true, message: '请输入作者', trigger: 'blur' }
        ],
        photo: [
          { required: true, message: '请输入', trigger: 'blur' }
        ],
        categoryId: [
          { required: true, message: '请选择所属分类', trigger: 'blur' }
        ],
        summary: [
          { required: true, message: '请输入摘要', trigger: 'blur' }
        ],
        extractFrom: [
          { required: true, message: '请输入摘抄自', trigger: 'blur' }
        ]
      }
    }
  },
  watch: {
    'listQuery.appId': function(val) {
      this.fetchData()
      this.fetchCategories()
    }
  },
  created() {

  },
  methods: {
    async fetchCategories() {
      var res = await this.$store.dispatch('thirdWechatResourceCategoryTree', { appId: this.listQuery.appId, type: 4 })
      this.categories = res
    },
    // 表格自带方法开始
    /* 全选/反选*/
    handleSelectionChange(val) {
      this.multipleSelectionRecords = val
    },
    /* 表格行数据单击*/
    handleRowClick(row) {
      this.$refs.multipleTable.toggleRowSelection(row)
    },
    /* 表格列排序*/
    sortChange(data) {
      const { prop, order } = data
      if (prop) {
        if (order === 'ascending') {
          this.listQuery.sort = '+' + prop
        } else {
          this.listQuery.sort = '-' + prop
        }
      } else {
        this.listQuery.sort = this.common.SORT_DEFAULT
      }
      this.handleFilter()
    },
    // 表格自带方法结束

    /* 搜索*/
    handleFilter() {
      this.listQuery.page = 1
      this.fetchData()
    },
    /* 重置*/
    handleReset() {
      this.listQuery = {
        ...this.listQuery,
        page: 1,
        limit: this.common.PAGE_LIMIT_DEFAULT,
        keyword: undefined,
        sort: this.common.SORT_DEFAULT
      }
      this.fetchData()
    },
    async fetchData() {
      this.listQuery = {
        ...this.listQuery,
        resourceType: 4
      }
      const response = await this.$store.dispatch('thirdWechatArticlePage', this.listQuery)
      this.list = response.records
      this.total = response.total
    },
    /* 新增*/
    handleCreate() {
      this.thirdWechatArticleRecord = {
        leavingMessage: 0,
        isOriginal: 1,
        attachment1: [],
        appId: this.listQuery.appId,
        resourceType: this.listQuery.resourceType
      }
      this.sideBox.status = 'create'
      this.sideBox.recordShow = true
      this.sideBox.title = '新增图文'
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    createData() {
      this.$refs['dataForm'].validate(valid => {
        if (valid) {
          const tempData = Object.assign({}, this.thirdWechatArticleRecord)
          tempData.attachment = tempData.attachment1.join(',')
          delete tempData.attachment1
          this.$store.dispatch('thirdWechatArticleSave', tempData).then(response => {
            this.sideBox.recordShow = false
            this.msgSuccess('创建成功')
            this.handleReset()
          }).catch(() => {
            this.sideBox.recordShow = true
          })
        }
      })
    },
    /* 编辑*/
    handleUpdate(row) {
      this.thirdWechatArticleRecord = Object.assign({}, row) // copy obj

      this.sideBox.status = 'update'
      this.sideBox.recordShow = true
      this.sideBox.title = '编辑图文'
      this.$nextTick(() => {
        this.$store.dispatch('thirdWechatArticleGetDetailsById', row.id).then(res => {
          this.thirdWechatArticleRecord = {
            ...this.thirdWechatArticleRecord,
            attachment1: this.thirdWechatArticleRecord.attachment === null ? [] : this.thirdWechatArticleRecord.attachment.split(','),
            contentBody: res.contentBody == null ? '' : res.contentBody
          }
        }).catch(() => {})
        this.$refs['dataForm'].clearValidate()
      })
    },
    updateData() {
      this.$refs['dataForm'].validate(valid => {
        if (valid) {
          const tempData = Object.assign({}, this.thirdWechatArticleRecord)
          this.$store.dispatch('thirdWechatArticleUpdate', tempData).then(response => {
            this.sideBox.recordShow = false
            this.msgSuccess('修改成功')
            this.handleFilter()
          }).catch(() => {
            this.sideBox.recordShow = true
          })
        }
      })
    },

    /* 删除*/
    handleRemoveSingle(row) {
      this.multipleSelectionRecords = []
      this.multipleSelectionRecords.push(row)
      this.$refs.multipleTable.clearSelection()
      this.$refs.multipleTable.toggleRowSelection(row, true)
      this.removeRecord()
    },
    removeRecord() {
      if (this.multipleSelectionRecords.length > 0) {
        const ids = []
        this.multipleSelectionRecords.forEach(function(v, i) {
          ids.push(v.id)
        })
        this.$confirm('此操作将永久删除记录, 是否继续?', '删除提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.$store.dispatch('thirdWechatArticleRemove', ids).then(response => {
            this.handleReset()
            this.msgSuccess('删除成功')
          }).catch(() => {})
        }).catch(() => { })
      } else {
        this.msgWarning('请选择要删除的记录')
      }
    }

  }
}
</script>
<style lang="scss" scoped>
</style>
